package cn.zzzhy.core.db;

import cn.zzzhy.core.db.builder.ISQLBuilder;
import cn.zzzhy.core.db.builder.impl.MySQLSQLBuilder;
import cn.zzzhy.core.db.executor.SQLExecutor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;

/**
 * author:zzzhy
 * since :15/11/9.
 */
public final class DB {

    public <T> RowMapper<T> buildRowMapper(Class<T> clazz) {
        return new DBBeanPropertyRowMapper<T>(clazz);
    }

    public enum Type{
        MYSQL(MySQLSQLBuilder.class);
//        ORACLE,
//        MONGODB,
//        REDIS;

        Type(Class<? extends ISQLBuilder> clazz) {
            this.clazz = clazz;
        }

        private final Class<? extends ISQLBuilder> clazz;

        public ISQLBuilder getSQLBuilder() {
            try {
                return clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private Type type;
    private JdbcTemplate jdbcTemplate;

    public DB(DataSource dataSource){
        this(dataSource,Type.MYSQL);
    }

    public DB(DataSource dataSource ,Type type){
        this.type= type;
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public Query from(String tableName){
        return new Query(this, jdbcTemplate, type.getSQLBuilder()).from(tableName);
    }

    public Query from(Class<?> tableClazz){
        return new Query(this,jdbcTemplate,type.getSQLBuilder()).from(tableClazz);
    }

    public <T> int insert(T entity) throws IllegalAccessException {
        return getSQLExecutor(entity).insert(entity);
    }

    private <T> SQLExecutor<T> getSQLExecutor(T entity) {
        return new SQLExecutor<T>(jdbcTemplate, (Class<T>) entity.getClass());
    }

}
